//获得全部节点
var autoNodes=[],getCharIndex=0;
var addAutoing=false;
var getIds=[];

var ancAlign = 0;//祖先对齐
var ancNumber=0;//祖先级数
var shaftNode=null;//轴节点
function autoMarge($sroot){
    if(!addAutoing){
        addAutoing=true;
        getCharIndex=0;
        autoNodes=[];
        autoNodes[autoNodes.length]=$root;
        var groot= parseInt($sroot.shidai);
        var chartgene=parseInt($(".settingDaisu").val());
        chartgene--;
        for(var j =0;j<$nodeIds.length;j++){
            var id =$nodeIds[j];
            var $node= $nodes[id];
            if($node.sex=="1"){//TODO 通过姓氏判断是否相同
                var ngene= parseInt($node.shidai);
                if( ngene%chartgene==groot ){
                    var h =false;
                    for(var j1=0;j1<autoNodes.length;j1++){
                        if(autoNodes[j1].id==$node.id){
                            h=true;
                            break;
                        }
                    }
                    if(!h)
                    {
                        autoNodes[autoNodes.length]=$node;
                    }
                }
            }
        }
        addAutoing=false;
    }
}
var getCharts=0;
var $chartStartNode;//开始节点
function goNextToPedigree(){
    getCharIndex++;
    if($(".auto_chart:checked").val()==0)
    {
        var url ='/index.php?a=jiapubook&type=shixipicZip&token='+$token+'&jiapu='+$jiapu.id+'&nodeids='+getIds.join(",");
        layer.closeAll();
        layer.open({
            type: 1,
            title: "世系图合成完成 点击下面按钮下载",
            shadeClose: false,
            closeBtn: 1,
            shade: 0.3,
            maxmin: false, //开启最大化最小化按钮
            area: ['300px', '200px'],
            content:"<a href='"+url+"'  style='margin:20px;'>下载世系图</a>",
        });
        return ;
    }
    if(getCharIndex>=autoNodes.length){
        if(getCharts==0){
            alert("没有有效的世系图,请选择其他节点进行合成");
        }
        //处理合成完成的步骤
            //alert('生成完成');
            var url ='/index.php?a=jiapubook&type=shixipicZip&token='+$token+'&jiapu='+$jiapu.id+'&nodeids='+getIds.join(",");
            layer.closeAll();
            layer.open({
                    type: 1,
                    title: "世系图合成完成 点击下面按钮下载",
                    shadeClose: false,
                    closeBtn: 1,
                    shade: 0.3,
                    maxmin: false, //开启最大化最小化按钮
                    area: ['300px', '200px'],
                    content:"<a href='"+url+"'  style='margin:20px;'>下载世系图</a>",
            });
        return ;
    }
    var $node= autoNodes[getCharIndex];
    $(".chart-nodeid").val($node.id);
    $(".settingRoot").val($node.honorific);
    pedigreeChart();
}

function pedigreeChart(){        
    loading("正在合成【"+$(".settingRoot").val() +"】世系图");                      
    var data = $("#settingPicture").serialize();
    $.getJSON("/index.php?a=jiapu&type=loadpicturenodes", data, function (e) {

            layer.closeAll();
            //removeBox();
            var data= e.data;              
            $zupu= data.zupu;
            $nodeIds={};
            var c2=currentScale;    
            
            $(".zupuname").text($zupu.title);
            $(".all-number").text(data.nodeTotal);
            $nodes= data.nodes;
            $nodeIds=data.ids;
            var shidai={};
            var number=0;
            $root=data.root;
            isShiXiTu=1;
            joinNodes();
            shaftNode= data.startNode;           
            for(var id in $nodes){
                if(!shidai[$nodes[id].shidai]){
                    number++;
                    shidai[$nodes[id].shidai]=1;
                    if(number>1){
                        break;
                    }
                }
            }
            if(number<2){
                goNextToPedigree();
                return;
            }
            $chartStartNode=data.startNode;
            getIds[getIds.length]= $chartStartNode.id;
            $zpNodess=data.zpNodes;
            $nodeIds=data.ids;
            $nodeIds=data.ids;
            $nodes=data.nodes;
            try
            {
                families={};
                onlyFamilies={};
                geneFamilies={};
                geneHeightAdd = {};
                //节点添加的高度
                nodeAppendHeight = {};
                nodeAppendWidth = {};
                //节点底部
                nodeBottomAppend = {};
                xsf = 0.3;
                ysf = 0.5;
                allReset();
                nodeSmall=$(".xiaozi:checked").val();
                if(nodeSmall==1)
                {
                    nwidth=50;
                    nheight=75;
                    lineSplit=2;
                    $("#translate-group").addClass("small");
                }
                $("#translate-group").addClass('shixitu-div');
                allDraw();
                autoSearch();
                if($("[name=wz]:checked").val()){
                    c2=0.5
                }
                else{
                    c2=1;
                }
                getCharts++;
                zoomDisplay(c2,1);
                console.log('gotu chart  '+ $root.id);
                ancAlign = $(".shangjie:checked").val();
        
                ancNumber= $(".parentNum").val();
                //轴节点
                //goNextToPedigree();
                //清理目录
                //高级设置 进行 设置  
                reRenderingShiXiPic();
        
                toPedigreeChart( getJPShowName( $root)+"世系图",1 ,$root);
            }
            catch(e){
                console.log(e.stack);
                alert(e);
                /*
                description: 错误描述 (仅IE可用). 
                fileName: 出错的文件名 (仅Mozilla可用). 
                lineNumber: 出错的行数 (仅Mozilla可用). 
                message: 错误信息 (在IE下同description) 
                name: 错误类型. 
                number: 错误代码 (仅IE可用). 
                stack: 像Java中的Stack Trace一样的错误堆栈信息 (仅Mozilla可用). 
                */  
            try
            {
                console.log("name:"+ e.name +" fileName:"+e.fileName+" lineNumber:"+e.lineNumber);
             }
             catch(e){}
                goNextToPedigree();
                return;
            }
    });
}

$(".btn-setting").click(function (e) {
      for(var j in $nodes){
        var node = $nodes[j];
        var val= $(".settingRoot").val();

        if( getJPShowName($nodes[j])== val || node .truename== val || node .honorific==val){
            getCharts=0;
            autoMarge($nodes[j]);
            pedigreeChart();       
            return ;
        }
    }
    alert('没有匹配的数据');

});
$advanced={'userempty':1}
/**
 重新画世系图
*/
var reRenderingShiXiPic=function(){
   
    for(var $nodeid in $nodes){
        var n =$nodes[$nodeid];
        var nodeContainer=$("[nodeid="+$nodeid+"]");
        if(n.sex==1){
        
         if(sxSetting.sorttext==1){
                var str=  getNodeDiaoTuSortText(n,sxSetting);      
                nodeContainer.append("<div class='left-node shu-node sorttext'>"+str+"</div>");
            }
         }
         if(sxSetting.zhiwu==1){
            if(n.oldxueli){
                nodeContainer.append("<div class='zhiwu left-node shu-node'>"+n.oldxueli+"</div>");
            }
            if(n.zhicheng){
                nodeContainer.append("<div class='zhiwu left-node shu-node'>"+n.zhicheng+"</div>");
            }
        
        }
        if(sxSetting.waiqian==1){
            if(n.sex==1){
                if(n.iswangwai==1 && n.wangwai){
                      nodeContainer.append("<div class='wifeinfo right-node shu-node'>"+"迁"+ n.wangwai+"</div>");
                }
            }
        }
        if(sxSetting.spousejoin==1)
        {
            if(n.sex==1)
            {
                var sp= spouseList[$nodeid];
                if(sp && sp.wifes)
                {
                    var w =sp.wifes;
                    for(var j=0;j<w.length;j++){
                        var w1 =w[j];
                        var text="";
                        if(j>0){
                            text+="续";
                        }
                        var wnode =$nodes[w1];
                        if(wnode)
                        {
                            text += wnode.alive==1?"配":"妣";

                            var xing =leaveBlankSpace(wnode.xing);
                            if(sxSetting.nvname==1){
                                name = (xing?xing :"     ")  + (wnode.truename?wnode.truename:"氏");
                                text+=text;
                            }
                            else{                            
                                if(xing)
                                {
                                    if(xing.trim()=="")
                                    {
                                        text="";
                                    }
                                    else
                                    {
                                        text += (xing?xing :"     ") + "氏";
                                    }
                                }
                                else if(wnode.truename){
                                    text += wnode.truename;
                                }
                                else{
                                    text+=" 氏";
                                }
                            }
                            
                            if(sxSetting.soncnt==1)
                            {
                                var spW =spouseList[w1];
                                if(spW){
                                    //处理方式方法
                                    var n =spW.sons.length;
                                    if(n>0){
                                        text+="生"+chineseNumber[n] +"子";
                                    }
                                }
                            }
                            nodeContainer.append("<div class='wifeinfo right-node shu-node'>"+text+"</div>");
                        }
                    }
                }
            }
        }
        var lnodes= nodeContainer.find(".left-node");
        if(lnodes.length>0)
        {
            for(var j=0;j<lnodes.length;j++){
                $(lnodes[j]).addClass("left-node-"+(lnodes.length-j));
            }
        }
        var rnodes= nodeContainer.find(".right-node");
        if(rnodes.length>0)
        {
            for(var j=0;j<rnodes.length;j++){
                $(rnodes[j]).addClass("right-node-"+(j+1));
            }
        }
        var n =$nodes[$nodeid];
        if(n.sex==1)
        {
            var i=0;
            var si =spouseList[$nodeid];
            if(si){
                //判断是否无后
               if(si.unOffSetting(sxSetting.nosonmark)){
                    i++;
                    nodeContainer.find(".female").append("<div class='appendInfo nosonmark' data-num='1'><img src='/assets/jiapu/shixitu/yuan_01_100.png'></div>");
               }
            }  
            if(n.relationship==2 && sxSetting.jichumark==1){
                 i++;   
                 nodeContainer.find(".female").append("<div class='appendInfo fuchu'  data-num='1'><img src='/assets/jiapu/shixitu/sanjiao_xia_01.png'></div>");
            }
            if(n.relationship==3 && sxSetting.jirumark==1){
                i++;
                nodeContainer.find(".female").append("<div class='appendInfo fujin' data-num='1'><img src='/assets/jiapu/shixitu/sanjiao_shang_100.png'></div>");
            }
            if(n.sex==1 && sxSetting.marknan==1){
                i++
                nodeContainer.find(".female").append("<div class='appendInfo mark-nan' data-num='1'><img src='/assets/jiapu/shixitu/mark-nan-100.png'></div>");
            }
            
            var l = $(nodeContainer.find(".appendInfo"));
            l.attr('data-num',i);
            if(i>1){
                l.addClass("appendInfo"+l.length);
                l.remove();
                var c  ="append_container_"+i;
                nodeContainer.find(".female").append("<div class='"+c+"'></div>")
                nodeContainer.find("."+c).append(l);

            }
        }
        else{
            if(sxSetting.marknv==1){
                i++
                nodeContainer.find(".female").append("<div class='appendInfo mark-nv' data-num='1'><img src='/assets/jiapu/shixitu/mark-nv-100.png'></div>");
            }
        }
        
    }
    getAllNodeHeight();
    //清理后重新画
    if(sxSetting.noborder==1){
        $(".tree-node-info").css({"border":"none"});
    }
    if(sxSetting.shidai==0){
        $(".ajp_scale").hide();
    }
    else{
        //重新计算高度
        $(".sc_item").each(function(){
            var gene = parseInt( $(this).attr("scalegene"));
            var h =$(this).height();
            if(sxSetting.jiantou==1){
                h += 20;
            }
            if(geneHeightAdd[gene]){
                //大或者小  先计算大的
                h +=geneHeightAdd[gene];
            }    
            $(this).css({"height":h+"px","line-height":h+"px"});
            $(this).find(".text_size_big").css({"text_size_big":h+"px"});
            $(this).find("span").css({"margin-top":"auto"});
        });
    }

 
    //从右到左
    if(sxSetting.rightbig==1){
        //列表移动
        var listGene={};
        //节点移动
        var nodesMove={};
        for(var gene in geneNodeList){
            var node = geneNodeList[gene][0];
            var id =node.id;
            var datas=[];
            var ids ={};
            var idNode =nodesById[id];
            var nodeids={};
            while(idNode){
                if(nodeids[idNode.id])
                {
                    break;
                }
                if(nodesById[idNode.id])
                {
                    datas[datas.length] =idNode;
                }
                nodeids[idNode.id]=1;
                if(idNode.right){
                    idNode= idNode.right;
                }
                else{
                    break;
                }
            }
        }
    } 
    if(sxSetting.spousejoin==1){
        var deleteIds=[];
        for(var nid in $nodes){
            var n =$nodes[nid];
            if(n.marryinto==1){
                if(!nodesById[nid]){
                    continue;
                }
                var nids={};
                var w = (1+xsf)*nwidth;
                var m =nodeAppendWidth[n.id];
                if(m) w+=m;

                var r = geneNodeList[n.shidai][0].id;
                var node1= nodesById[nid];
                
                while(node1.right){
                    if(node1.right.id == n.id){
                        break;
                    }
                    node1= node1.right;
                    //nodesById[node1.id].x-=m;
                    //node1.x+=m;
                }
                deleteIds[deleteIds.length]= nid;
                //right 往左移动多少位
            }
        }
        for(var j=0;j<deleteIds.length;j++){
            var nid =deleteIds[j];
            $("[nodeid="+nid+"]").remove();
            delete(nodesById[nid]);
            delete($nodes[nid]);
        }
    }
    
    if(sxSetting.rightbig==1){
        correctedXM();
    }
    else{
        correctedX();
    }
   
   for(var j in nodesById){
        $("[nodeid="+j+"]").css({"left":nodesById[j].x+"px","top":nodesById[j].y+"px"});
   }
   //重新计算画布大小 边界值
   jpMaxY = jpMaxX=-10000*1000,
   jpMinY = jpMinX=10000*1000;
   for(var id in nodesById){
        var b = nodesById[id];
        if(b){
            if(jpMaxY<b.y) 
            {
                jpMaxY =b.y;
            }
            if(jpMinY>b.y) jpMinY =b.y;
            if(jpMaxX<b.x) jpMaxX= b.x;
            if(jpMinX>b.x) jpMinX =b.x;
        }
       
   }
    if(sxSetting.nodetrans==1){
        $(".full-name-t,.tree-node-info").css({"background-color":"rgba(255, 255, 255, 0)"});
    }
    if(sxSetting.fontcolor){
         $(".female,.female div,.tree-node-info,.tree-node-info div,.shu-node").css({"color": sxSetting.fontcolor});
    }
    if(sxSetting.bold==1){
             $(".full-name-t,.tree-node-info").css({"font-weight": "bolder"});
    }
      if(sxSetting.shidaicolor){
         $(".sc_item span").css({"color": sxSetting.shidaicolor});
    }

    if(sxSetting.fontfamily){
            $(".sc_item span,.female,.female div,.tree-node-info,.tree-node-info div,.shu-node").css({"font-family": sxSetting.fontfamily});
    } 
}
var goDraw=function(){
     for(var id in $nodes){
        $("[nodeid="+id+"]").css({"left": nodesById[id].x +"px","top":nodesById[id].y+"px"});
     }
}


//纠正 左边你的节点
var moveGeneLeft=function(gene){
    if(!geneNodeList[gene]){
        console.log('没有匹配的节点'+gene);
        return ;
    }
    var gRoot= geneNodeList[gene][0];
    var gnode=gRoot;
    var family =families[gnode.id];
    while(!family && gnode.right){
        gnode= gnode.right;
        family =families[gnode.id];
    }

    var list= geneFamilies[gene];
   
    var getid={};
    while(family){
        moved = {};
        if(getid[family.mainid()]){
            break;
        }
        getid[family.mainid()]=1;
        jiaoFamily(family);
        var right = family.rightFamily();
        if(right && right.mainid()!=gRoot.id)
        {
            jiaoFamily(right);
            var sMin=  family.minX();
            var oMax= right.maxX();
            if(sMin<oMax +  (1+xsf)*nwidth){
                moved = {};
                movel= sMin -oMax - (1+xsf)*nwidth;
                right.move(movel);          
                jiaoAncestors(right);
                if(right.sons.length==1){
                    var c = families[right.sons[0].id];
                    if(c)
                    {
                        var sn= nodesById[c.mainid()];
                        var ln= nodesById[right.mainid()];
                        var m =ln.x- sn.x;
                        moved={};
                        c.move(m);
                    }
                }
            }
            family =right;
        }
        else{
            break;
        }
    }
}

//校正水平位置
var correctedXM = function () {
    families = {};
    onlyFamilies = {};
    geneFamilies = {};
    var geneMin = 15000, geneMax = -1100;
    for (var k = 0; k < jpnodes.length; k++) {
        var n = jpnodes[k];
        var id = n.id;
        var dnode =nodesById[id];
        if(!dnode){
            continue;
        }
        var f = families[id];
        if (!f) {
            family = addFamliy(n);
            var gene = n.gene;
            if (geneMax < gene) { geneMax = gene; }
            if (geneMin > gene) { geneMin = gene; }
            //处理数据
            if (!geneFamilies[gene]) {
                geneFamilies[gene] = [];
            }
            geneFamilies[gene][geneFamilies[gene].length] = family;
            
        }
    }
    
 

    for (var gene = geneMax; gene >= geneMin; gene--) {
        var list = geneFamilies[gene];
        if (list) { 
            moveGeneLeft(gene);
        }
    }     
    //对内缩
    for (var gene = geneMax; gene >= geneMin; gene--) {
        var list = geneFamilies[gene];
        if (list) {
            var gRoot= geneNodeList[gene][0];
            var gnode=gRoot;
            var family =families[gnode.id];
            while(!family && gnode.right){
                gnode= gnode.right;
                family =families[gnode.id];
            }
            //var family =families[gRoot.id];
            var getid={};
            while(family){
               moved = {};
               if(getid[family.mainid()]){
                    break;
               }
               getid[family.mainid()]=1;
               jiaoFamily(family);
               var right = family.rightFamily();
               
               if(right && right.mainid()!=gRoot.id)
               {
                    var max = null;
                    var mainid = family.mainid();
                    var getids={};
                    var goRight=null;
                    while(right) {
                        var mainRight = right.mainid();
                        if(getids[mainRight] || mainRight ==gRoot.id){
                            break;
                        }
                        getids[gRoot.id]=1;
                        if(mainRight== mainid){
                            break;
                        }
                        var match = $nodes[mainRight].father == $nodes[mainid].father;
                        if (match) {
                            console.log(family.mainid() + "  right:" + mainRight);
                            //处理压缩
                            for (var g1 = gene; g1 <= geneMax; g1++) {
                                var rMin = family.geneMin(g1);
                                var lMax = right.geneMax(g1);
                                if (lMax === null || rMin === null) {
                                    continue;
                                }
                                if (rMin - lMax < max || max === null) {
                                    max = rMin - lMax;
                                    goRight =right;                          
                                }
                                console.log("g:" + g1 + " max:" + max + " rmin:" + rMin + " lmax:" + lMax);
                            }
                        }
                        else {
                            break;
                        }
                        right= right.rightFamily();
                    }

                    if (max !== null) {
                        if (max != xsf * nwidth) {
                            //往右判断
                            var goLeft=goRight.leftFamily();
                            var max2=null;
                            while(goLeft){
                                var mid =goLeft.mainid();
                                if(mid==family.id){
                                    break;
                                }
                                if($nodes[mid].father!=$nodes[goRight.mainid()].father)
                                {
                                    break;
                                }
                                for (var g1 = gene; g1 <= geneMax; g1++) {
                                    var rMin = goLeft.geneMin(g1);
                                    var lMax = goRight.geneMax(g1);
                                    if (lMax === null || rMin === null) {
                                        continue;
                                    }
                                    if (rMin - lMax < max2 || max2 === null) {
                                        max2 = rMin - lMax;
                                    }
                                }
                                goLeft= goLeft.leftFamily();
                            }
                            if(max2 && max2< max ){
                                max=max2;
                            }
                            var movel = max- xsf * nwidth ; 
                           
                            moved = {};
                            moved[family.mainid()]=1;
                            var r = nodesById[ goRight.mainid()];
                            var l= nodesById[ family.mainid()];
                            jiaoFamily(goRight);
                            console.log('before move left:['+l.id+']['+l.name+']['+l.x+'] ,right:['+r.id+']['+r.name+']['+r.x+']');
                            goRight.move(movel);
                            console.log('after move  left:['+l.id+']['+l.name+']['+l.x+'] ,right:['+r.id+']['+r.name+']['+r.x+']');
                            jiaoFamily(goRight);
                            $("[nodeid="+family.mainid()+"]").attr('neisuo',movel);
                            if(goRight.maxX()>family.minX()){
                                goRight.move(family.minX()- goRight.maxX());
                            }
                            jiaoAncestors(goRight);
                            if(goRight.sons.length==1){
                                var c = families[goRight.sons[0].id];
                                if(c)
                                {
                                    var sn= nodesById[c.mainid()];
                                    var ln= nodesById[goRight.mainid()];
                                    var m =ln.x- sn.x;
                                    moved={};
                                    c.move(m);

                                    //$("[nodeid="+c.mainid()+"]").attr('c neisuo',movel);
                                }
                            }
                            family=goRight;
                            continue;
                        }
                    }
                   family = family.rightFamily();
               }
               else{
                    break;
               }
            }  
        }
    }
    var rootFamily = families[$root.id];
    if (rootFamily) {
        jiaoFamily(rootFamily);
    }
}



/* 获得所有节点的添加的高度 */
var getAllNodeHeight=function(){
    for(var nodeid in $nodes){
        getNodeAppendHeight(nodeid);
    }
    for(var nodeid in $nodes){
        var appendHeight= nodeAppendHeight[nodeid];
        if(appendHeight)
        {
            var node =$nodes[nodeid];
            var shidai = parseInt(node.shidai);
            if(geneHeightAdd[shidai]){
                var m =geneHeightAdd[shidai];
                if(m<appendHeight){
                    geneHeightAdd[shidai]= appendHeight;
                }
            }
            else{
                geneHeightAdd[shidai]= appendHeight;
            }
        }
    }
    //重新调整高度
    var gAppendTrueHeight={};
    var goAdd=0;
   
    var start=10000;
    for(var nnid in $nodes){
        var n = $nodes[nnid];
        if(parseInt(n.shidai)<start){
            start= parseInt(n.shidai);
        }
    }
    for(var j=0;j<1000;j++){
        var h =0;
        if(sxSetting.jiantou==1){
            h=(j-start)*20;
        }
        for(var g in geneHeightAdd){            
            if( g < j ){
                h += geneHeightAdd[g];
            }
            else{
                break;
            }
        }
        gAppendTrueHeight[j]=h;
    }
    //开始批量进行调整高度
    for(var $nodeid in $nodes){
        var n =$nodes[$nodeid];
        var appH= gAppendTrueHeight[parseInt( n.shidai)];
        if(appH){
            var nodeEntity= nodesById[$nodeid];
            nodeEntity.y+=appH;
         
        }
    }
    //纠正家庭位置
}
 
//获得节点 增加的高度
var getNodeAppendHeight=function(nodeid){
    var con=$("[nodeid="+nodeid+"]");
    var appendHeight=0;
    if(con.find(".moreFonts").length>0){
        var r =$(con.find(".moreFonts")).attr('name-text').length;
        appendHeight= (r-2)*69;
    }
    if(con.find(".appendInfo").length>0){
        appendHeight+=40;
    }
    if(appendHeight){
           nodeBottomAppend[nodeid]=appendHeight;
    }
    var oldapph = appendHeight;
    var oldh= h = parseInt(nheight)+appendHeight;
    var r= con.find(".shu-node");
    if(r.length>0){
        for(var j=0;j<r.length;j++){
            var h2 = $(r[j]).height()+20;
            if(h2>h){
                appendHeight = h2-nheight;
                h= h2;
            }
        }
        $nodes[nodeid].appendWidth = nodeAppendWidth[nodeid] = r.length*50;
    }
   
    var c =con.find(".right-node");
    if(c.length>0){
         nodeRightAppendWidth[nodeid ] = c.length*50;
         var rh=0;   
         for(var j=0;j<c.length;j++){
            var h2 = $(c[j]).height()+20;
            if(h2>oldh ){
                if(h2-oldh>rh)
                {
                    rh = h2-oldh;
                }
            }
        }
        if(rh>0){
            nodeRightHeightAppMax[nodeid]=rh;
        }
        var r =c.length*40;
        if(nodesById[nodeid]){
            if(sxSetting.rightbig==0){
                nodesById[nodeid].x+=r;
            }
        }
        moveNodes={};
        getBoforeNodes(nodeid);
        //他后面的进行移动
        afterNodeMoveX(nodeid,r);
    }
    var c =con.find(".left-node");
    if(c.length>0){
         nodeLeftAppendWidth[nodeid ] = c.length*50;
         var rh=0;   
         for(var j=0;j<c.length;j++){
            var h2 = $(c[j]).height()+20;
            if(h2>oldh){
                if(h2-oldh>rh)
                {
                    rh = h2-oldh;
                }
            }
        }
        if(rh>0){
            nodeLeftHeightAppMax[nodeid]=rh;
        }
        var r =c.length*40;
        if(nodesById[nodeid]){
            if(sxSetting.rightbig==1){
                nodesById[nodeid].x+=r;
            }
        }
        moveNodes={};
        getBoforeNodes(nodeid);
        afterNodeMoveX(nodeid,r);
    }
    if(appendHeight>0){
        nodeAppendHeight[nodeid]= appendHeight;
    }
}
///移动完的节点
var moveNodes={}; 
var getBoforeNodes=function(nodeid){
    //moveNodes[nodeid]=1;
    var n =nodesById[nodeid];
    while(n && n.left){
        moveNodes[n.id]=1;
        n=n.left;
    }
}
var afterNodeMoveX=function(nodeid,x){
    moveNodes[nodeid]=1;
    if(nodesById[nodeid])
    {
        var r =nodesById[nodeid].right;
        while(r){ 
            if(moveNodes[r.id]){
                break;
            }
            r.x +=x;
            r= r.right;
        }
    }
}



    //获得 图片的部分
var toPedgreeChartingParts=function(name ,x, y,width,pageNumber){
 
        //处理顶部节点对齐
    if(ancNumber>0 && ancAlign)
    {
        changeNodePosition=function(){
            //处理内容
            var cnode= shaftNode;
            var x = nodesById[cnode.id].x;
            for(var  jn=0;jn<ancNumber;jn++){
                var p = cnode.father;
                var pnode= $nodes[p];
                if(!pnode)break;
                var div=$("[nodeid="+pnode.id+"]");
                if(div.length>0){
                    div.css({"left": x+"px"});
                    var m = nodesById[pnode.id];
                    m.x=  x;
                    if(m.spouse){
                        for(var sj=0;sj<m.spouse.length;sj++){
                            var ss =m.spouse[sj];
                            ss.x= x+(1+xsf)*nwidth*(sj+1);
                            //$("[nodeid="+ss.id+"]").css({"left":ss.x+"px"});
                        }
                    }
                }
                else{
                    break;
                }
                cnode=pnode;
            }
      
        }
    }
    $tg=$("#translate-group");
    $tg.css({"background-color":"#fff"});
    $body=$tg;

    var aHeight= 1123;
    var aWidth =  $cont.width();
    if(aWidth+x > (jpMaxX+600-jpMinX)*currentScale ){
        aWidth= (jpMaxX+600-jpMinX)*currentScale-x;
    }
    var onePic=false;
    if($(".onepic:checked").val()==1){
        aHeight= jpMaxY-jpMinY+200;
        aWidth=jpMaxX-jpMinX+200;
        onePic=true;
        aHeight+=200;
        aWidth+=200;
        aHeight*=currentScale;
        aWidth*=currentScale;
      
    }
    var scale=3;
    var width1=(jpMaxX+600-jpMinX)*currentScale;
   
 
    if($(".yangtu:checked").val()==1){
        scale=1;
    }
    

    console.log(" 合成图片高度宽度 x:"+aWidth +"  y:"+aHeight);
   
    setTimeout(function(){
        console.log("合成图片【"+name +"】 numb:【"+pageNumber+"】 x【"+x +"】 y:【"+y+"】 w:【"+ width+ "】"); 
        $tg=$("#translate-group");
        linkWidth=20;
        linkColor="#000";
        console.log("minX "+jpMinX);
        var paddingleft=60;
        var left = x  + (jpMinX-200-paddingleft)*currentScale;
        
        

        $tg.css({'left':(-left)+"px",'top':(20-y)  + "px"});
        if($(".ajp_scale").length>0){
            //var left=$("#translate-group").css("left");
            //var str=  jpMinX/currentScale;
            if(x==0){
                $(".ajp_scale").css({'left':"0px"});
                $(".ajp_scale").css({'left':((left+paddingleft)/currentScale)+"px"});
                $(".sc_item").css({"background-color":"rgba(255,255,255,0)"});
                if(nodeSmall==1){
                    $(".ajp_scale").css({"top":"50px"});
                }
            }
        }
        links();
        if(onePic)
        {
                AfterMoveLink(aWidth/currentScale,aHeight/currentScale);
        }
        else{
            AfterMoveLink();
        }
        
        var canvas = document.createElement("canvas");
        var ratio=1;
        if(nodeSmall==1){
            //ratio=0.5;
        }  
        canvas.width = aWidth*scale*ratio;
        canvas.height = aHeight*scale*ratio;// height * 6;
        canvas.style.width = aWidth + "px";
        canvas.style.height = aHeight+ "px";
        canvas.style.top ='0px';//  x+ "px"; // '0px';
        canvas.style.left ='0px';//  y + "px"; // '0px';
        var context = canvas.getContext("2d");
        //然后将画布缩放，将图像放大两倍画到画布上
        context.scale(scale*ratio,scale*ratio);
        layer.closeAll(); 
        loading("世系图正在合成中..."+pageNumber);
        html2canvas( $body, {
            canvas: canvas,    
            onrendered: function (canvas) {
            try
            {      
                var data=canvas.toDataURL("image/png",1.0);
            }
            catch(e){
                    layer.closeAll();
                    alert("世系图合成出现问题，请稍后再试");
            }
            toPedigreeCharting=false;

            layer.closeAll();

            $.post("/index.php?a=ajax&type=uploadJiapu&ispost=1&picType=shixipic", { "scale":scale, 'src': data,'page':pageNumber,'nodeid':$chartStartNode.id,"height":aHeight*scale, "width":aWidth*scale, "name":name,"x":x*scale,"y":y*scale, 'jpguid':$jiapu.guid , 'token': $token }, function (e){
                e = jQuery.parseJSON(e); 
                if (e.success) {
                    setTimeout(function(){
                        //debugger;
                        if(x >= (jpMaxX-jpMinX+600)*currentScale || onePic){   
                            var allHeight= jpMaxY-jpMinY+400;
                        
                            console.log("all Height:["+allHeight+"]  cHeight:["+(aHeight+y)+"] currentScale:["+currentScale+"]");
                            if( (aHeight+y)/currentScale< allHeight){
                                y =aHeight+y;
                                x=0;
                                toPedgreeChartingParts(name , x,y,width, pageNumber+1);
                            }
                            else
                            {
                            //合并 图片
                                $.post("/index.php?a=jiapubook&type=margeShixiPic",{ 'allWidth':(jpMaxX-jpMinX+600),'allHeight':(jpMaxY-jpMinY)+600, "scale":currentScale*scale,'token':$token,'jiapu':$jiapu.id,'nodeid':$chartStartNode.id,"height":aHeight*scale},function(e){
                                    toPedigreeCharting=false;
                                    layer.closeAll();
                                    goNextToPedigree();//转移到下一个用户
                                });
                            }
                            return ;
                        }
                        else{
                            x+= aWidth;
                        }
                        toPedgreeChartingParts(name , x,y,width, pageNumber+1);
                    },1000);
                }
                else {
                    layer.closeAll();
                    alert(e.message);
                }
            })
        },
        height: aHeight,
        width: aWidth,
    });     
},2000);
};

var toPedigreeCharting=false;
var toPedigreeChart=  function (name) {
    if(!toPedigreeCharting){
        toPedigreeCharting=true;
        //removeBox();
         $.getJSON("/index.php?a=jiapubook&type=clearShiXiTu",{ 'nodeid':$chartStartNode.id,  'jiapu':$jiapu.id , 'token': $token },function(e){
                if(e.success)
                { 
                        var ac= $(".toPedigreeChart");
                        $dt=$(".downImage-text");
                        $dt.attr("text",$dt.text());
                        var op =currentScale;
                        $tg=$("#translate-group");
                        loading("世系图正在合成中...");
                        $(".header,.w1200").hide();
                        ac.attr("gooing",true);
                        $(".zoom-box").hide();
                        var width= $tg.width()+200;
                        toPedgreeChartingParts(name , 0,0,width, 1);;
                }
                else{
                    layer.closeAll();
                    alert(e.message);
                    return ;
                }
           });

        return;
    }
        
}; 